import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
//腐烂的苹果
public class demo4 {
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    public int rotApple (ArrayList<ArrayList<Integer>> grid) {
      int m =grid.size();
      int n = grid.get(0).size();
      boolean[][] vis = new boolean[m][n];

        Queue<int[]> q = new LinkedList<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid.get(i).get(j) == 2){
                    q.add(new int[]{i,j});
                }

            }
        }
        int ret = 0;
        while(!q.isEmpty()){
            int sz = q.size();
            while(sz-- != 0){
                int[] t = q.poll();
                int a = t[0],b = t[1];
                for (int k = 0; k < 4; k++) {
                    int x = a + dx[k],y = b + dy[k];
                    if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y]
                    && grid.get(x).get(y) == 1){
                        vis[x][y] = true;
                        q.add(new int[]{x,y});
                    }
                }
            }
            ret++;
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid.get(i).get(j) == 1 && !vis[i][j] ){
                    return -1;
                }

            }

        }
        return ret;
    }
}

